package com.sunshuo.springsecuritydemo.dao;

import com.sunshuo.springsecuritydemo.pojo.Menu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @ClassName MenuDao
 * @Description
 * @Author sunshuo
 */
@Repository
public class MenuDao {

    private JdbcTemplate jdbcTemplate;

    @Autowired
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public List<String> getAuthCodeByRoleNames(List<String> roleIds) {
        String sql = "select auth_code from t_role_menu role_menu  " +
                "left join t_role role on role.id = role_menu.role_id " +
                "left join t_menu menu on role_menu.menu_id = menu.id WHERE role.name in";
        sql += "(";
        for (int i = 0; i < roleIds.size(); i++) {
            sql += "?";
            if (i != roleIds.size() - 1) {
                sql += ",";
            }
        }
        sql += ")";
        return jdbcTemplate.query(sql, new RowMapper<String>() {
            @Override
            public String mapRow(ResultSet rs, int rowNum) throws SQLException {
                return rs.getString("auth_code");
            }
        }, roleIds.toArray());
    }

    public List<Menu> getAll() {
        String sql = "select * from t_menu";
        return jdbcTemplate.query(sql, new RowMapper<Menu>() {
            @Override
            public Menu mapRow(ResultSet rs, int rowNum) throws SQLException {
                Menu menu = new Menu();
                menu.setId(rs.getString("id"));
                menu.setTitle(rs.getString("title"));
                menu.setpId(rs.getString("pId"));
                menu.setAuthCode(rs.getString("auth_code"));
                return menu;
            }
        });
    }

}
